import Axios from 'axios'
import qs from 'qs'
import router from '~/routers/index'
import config from '~/config.js'
import { Message, Loading } from 'element-ui'

let loading

const STATUS_FAIL = 0
const STATUS_SUCCESS = 1
const STATUS_LOGIN = 2
const STATUS_APPLY = 3

const axiosCreate = Axios.create({
    //设置主要域名
    baseURL: config.hostSaas,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
})

// 拦截器
axiosCreate.interceptors.request.use(
    (options) => {
        loading = Loading.service({
            lock: true,
            text: '加载中……',
            background: 'rgba(0, 0, 0, 0.3)'
        })
        if (options.method === 'post') options.data = qs.stringify(options.data);
        // 是否需要带上企业id
        let params = {}
        //是否是无需登录信息的接口
        if (options.url.indexOf('/worker/job/show') > -1) {
            params.avoidAuthorization = true
        } else {
            if(localStorage.getItem('Authorization')){
                params.Authorization = localStorage.getItem('Authorization')
                params.avoidAuthorization = false
            }else{
                params.avoidAuthorization = true
            }

        }

        //是否具有企业资质
        if (localStorage.getItem('company')) {
            params.company = localStorage.getItem('company')
        }

        //带上domain参数
        params.domain = config.domain
        //带上port参数为pc
        params.port = 'pc'
        // header 带 Authorization和sass 地址
        options.headers = Object.assign(options.headers || {}, params)

        // logDebug.
        logDebug(options)

        return options
    },

    (err) => {
        defaultErrorHandler('请求错误', err, options)
        return Promise.reject(err)
    }
);

// 添加响应拦截器
axiosCreate.interceptors.response.use(
    (response) => {
        const options = response.config

        // 转换数据格式
        if (typeof response === 'string') {
            try {
                response = JSON.parse(response)
            } catch (err) {
                defaultErrorHandler('服务异常', err, options)
                return Promise.reject(err)
            }
        }

        // logDebug.
        logDebug(response)
        return handleResponse(response, options)
    },

    (err) => {
        const options = err.config


        defaultErrorHandler('网络错误', err, options)
        return Promise.reject(err)
    }
);

// 打印调试
function logDebug(data) {
    try {
        console.log(data)
    } catch (e) {}
}
// 默认错误处理
function defaultErrorHandler(tip, err, options) {
    Message.error(tip)
}

// 响应成功
function responseSuccess(response) {
    const data = response.data

    if (!data.data) {
        data.data = {}
    }

    // data.data.__info = data.info
    return data.data
}

// 响应失败
function responseFail(data, options) {
    Message.error(data.info)
}

// 响应需要登录
function responseLogin(response, options) {
    if (options.needLogin) {
        return login(options)
    } else {
        return Promise.reject(response)
    }
}

// 响应需要申请
function responseApply(data, options) {
    if (options.showApplyTips) {
        Message.success(`${data.info}\nhrId: ${data.data.hrId}\nuserId: ${data.data.userId}`)
    }
}

// 响应后处理
function handleResponse(response, options) {
    let data = response.data
    let { status } = data
    loading.close()
    if (status) {
        switch (status) {
            case -1: //未登录
            { //控制登陆模块
                // Taro.redirectTo({
                //     url: '/subPackages/subPackageS/authorize/authorize?type=getPhoneNumber'
                // })
                // store.dispatch(sign())   //未登录显示登陆模块
            }
            break;
        case 1: //登陆正常
        {
            // console.log(store.dispatch)
            // store.dispatch(signed())   //登陆正常隐藏登陆模块
            // 成功 (返回resolve)
            if (data.status === STATUS_SUCCESS) {
                response = responseSuccess(response)
                return Promise.resolve(response)
            }

            // 登录 (返回promise)
            if (data.status === STATUS_LOGIN) {
                return responseLogin(response, options)
            }

            // 失败 (返回reject)
            if (data.status === STATUS_FAIL) {
                responseFail(data, options)
                return Promise.reject(response)
            }

            // 申请 (返回reject)
            if (data.status === STATUS_APPLY) {
                responseApply(data, options)
                return Promise.reject(response)
            }
        }
        break;
        case 2: //未创建简历
        { //前往创建简历

        }
        break;
        case 0: //登陆异常请重试
        {
            Message.error(data.info)
        }
        break;
        }
    } else if (status == 0) {
        return Promise.reject(response.data.info)
    }
}


export default axiosCreate